package com.hupu.jrs.ui.browser

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import butterknife.BindView
import butterknife.ButterKnife
import com.hupu.jrs.R
import com.hupu.jrs.ui.BaseFragment
import com.hupu.jrs.widget.HuPuWebView

/**
 * Created by sll on 2016/3/11.
 */
class BrowserFragment : BaseFragment() {

    @BindView(R.id.webView)
    internal var webView: HuPuWebView? = null
    @BindView(R.id.progress)
    internal var progress: ProgressBar? = null

    private var url: String? = null
    private var title: String? = null
    private var external: Boolean = false

    override fun initInjector() {

    }

    override fun initContentView(): Int {
        return R.layout.fragment_browser
    }

    override fun getBundle(bundle: Bundle) {
        url = bundle.getString("url")
        title = bundle.getString("title")
        external = bundle.getBoolean("external")
    }

    override fun initUI(view: View) {
        ButterKnife.bind(this, view)
        showContent(true)
        webView!!.setWebChromeClient(object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                if (!TextUtils.isEmpty(this@BrowserFragment.title)) {
                    getActivity().setTitle(this@BrowserFragment.title)
                }
            }

            override fun onProgressChanged(view: WebView, newProgress: Int) {
                progress!!.progress = newProgress
                if (newProgress == 100) {
                    progress!!.visibility = View.GONE
                } else {
                    progress!!.visibility = View.VISIBLE
                }
            }
        })
        if (external) {
            webView!!.setWebViewClient(object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
                    if (url != null) view.loadUrl(url)
                    return true
                }
            })
        }
    }

    override fun initData() {
        webView!!.loadUrl(url!!)
    }

    fun reload() {
        webView!!.reload()
    }

    companion object {

        @JvmOverloads
        fun newInstance(url: String, title: String, external: Boolean = false): BrowserFragment {
            val mFragment = BrowserFragment()
            val bundle = Bundle()
            bundle.putString("url", url)
            bundle.putString("title", title)
            bundle.putBoolean("external", external)
            mFragment. setArguments(bundle)
            return mFragment
        }
    }
}
